package com.jijuxie.house.controller;

import com.jijuxie.common.core.R;
import com.jijuxie.framework.config.UploadConfig;
import com.jijuxie.house.domain.HouseImage;
import com.jijuxie.house.service.IHouseImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/house/image")
public class HouseImageController {

    @Autowired
    private IHouseImageService imageService;

    @Autowired
    private UploadConfig uploadConfig;

    /**
     * 上传房源图片
     */
    @PostMapping("/upload")
    public R<HouseImage> upload(@RequestParam("file") MultipartFile file, @RequestParam Long houseId,
            @RequestParam String imageType) throws IOException {
        try {
            System.out.println("上传图片，houseId=" + houseId + ", imageType=" + imageType);
            
            // 生成目录路径 - 确保目录存在
            String uploadPath = uploadConfig.getPath();
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                boolean created = uploadDir.mkdirs();
                if (!created) {
                    return R.fail("无法创建上传目录");
                }
            }
            
            // 特殊处理：如果houseId为-1，表示聊天图片，添加chat前缀
            String prefix = "";
            if (houseId != null && houseId.equals(-1L)) {
                prefix = "chat_";
                System.out.println("检测到聊天图片上传，houseId=" + houseId);
            }
            
            // 生成文件名
            String fileName = prefix + UUID.randomUUID().toString()
                    + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

            // 保存文件
            File dest = new File(uploadPath + fileName);
            file.transferTo(dest);

            // 生成URL
            String imageUrl = uploadConfig.getUrl() + fileName;
            
            // 创建返回对象
            HouseImage image = new HouseImage();
            image.setImageType(imageType);
            image.setImageUrl(imageUrl);
            
            // 特殊处理：如果houseId为负数或0，表示聊天图片，不保存到数据库，仅返回URL
            if (houseId == null || houseId <= 0) {
                System.out.println("聊天图片不保存到数据库，直接返回URL: " + imageUrl);
                return R.ok(image);
            }

            // 正常处理：保存房源图片信息到数据库
            System.out.println("普通房源图片，保存到数据库，houseId=" + houseId);
            image.setHouseId(houseId);
            imageService.save(image);

            return R.ok(image);
        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 批量上传房源图片
     */
    @PostMapping("/batchUpload")
    public R<List<HouseImage>> batchUpload(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam Long houseId,
            @RequestParam String imageType) throws IOException {
        List<HouseImage> imageList = new ArrayList<>();
        for (MultipartFile file : files) {
            HouseImage image = imageService.uploadImage(file, houseId, imageType);
            imageList.add(image);
        }
        return R.ok(imageList);
    }

    /**
     * 删除房源图片
     */
    @DeleteMapping("/{imageId}")
    public R<Void> remove(@PathVariable Long imageId) {
        imageService.removeById(imageId);
        return R.ok();
    }

    /**
     * 上传聊天图片 - 不需要关联房源
     */
    @PostMapping("/chat/upload")
    public R<String> uploadChatImage(@RequestParam("file") MultipartFile file) throws IOException {
        // 生成文件名
        String fileName = "chat_" + UUID.randomUUID().toString()
                + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

        // 保存文件
        File dest = new File(uploadConfig.getPath() + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        file.transferTo(dest);

        // 只返回图片URL，不保存到house_image表
        String imageUrl = uploadConfig.getUrl() + fileName;
        return R.ok(imageUrl);
    }
}
